/*
Binary clock
By: DanielQB
v0.12
*/

#include <Time.h> 

int i,j,a;

#define num_cols 6
int col[num_cols] = {42,40,38,36,34,32};

#define num_rows 4
int row[num_rows] = {30,28,26,24};

#define b1 50
#define b1 52


//T1305194711

#define TIME_MSG_LEN  11   // time sync to PC is HEADER followed by unix time_t as ten ascii digits
#define TIME_HEADER  'T'   // Header tag for serial time sync message
#define TIME_REQUEST  7    // ASCII bell character requests a time sync message 

int T[6];

void setup(){
  Serial.begin(9600);
//  setTime(01,45,00,10,05,2011);

  for(int i=0; i < num_rows; i++){
    pinMode(row[i], OUTPUT);
    digitalWrite(row[i], HIGH);
  }
  for(int j=0; j < num_cols; j++){
    pinMode(col[j], OUTPUT);
    digitalWrite(col[j], LOW);
  }
}

void loop(){
  if(Serial.available()){
    processSyncMessage();
  }
  
  T[0]=hour()/10;
  T[1]=hour()%10;
  T[2]=minute()/10;
  T[3]=minute()%10;
  T[4]=second()/10;
  T[5]=second()%10;
  
  for(i=0;i<6;i++){
    digitalWrite(col[i], HIGH);
/*    
    Serial.print(T[i]);  //debug1
    Serial.print("-");  //debug2b
    Serial.print(!digitalRead(col[i]));  //debug2b
    Serial.print(",");  //debug2b
*/
    for(j=0;j<4;j++){
      if(bitRead(T[i], j)==1)
        digitalWrite(row[j], LOW);
//      Serial.print(bitRead(T[i], j));  //debug2a
//        Serial.print(digitalRead(row[j]));  //debug2b
    }
//    Serial.print(" ");  //debug2b
//    delay(10);
    
    digitalWrite(col[i], LOW);
    digitalWrite(row[0], HIGH);
    digitalWrite(row[1], HIGH);
    digitalWrite(row[2], HIGH);
    digitalWrite(row[3], HIGH);
  }
//  Serial.println();
}

void processSyncMessage() {
  // if time sync available from serial port, update time and return true
  while(Serial.available() >=  TIME_MSG_LEN ){  // time message consists of a header and ten ascii digits
    char c = Serial.read() ; 
//    Serial.print(c);  
    if( c == TIME_HEADER ) {       
      time_t pctime = 0;
      for(int i=0; i < TIME_MSG_LEN -1; i++){   
        c = Serial.read();          
        if( c >= '0' && c <= '9'){   
          pctime = (10 * pctime) + (c - '0') ; // convert digits to a number    
        }
      }   
      setTime(pctime);   // Sync Arduino clock to the time received on the serial port
    }  
  }
}
